package auth.util

import auth.entity.SecUser
import org.apache.log4j.Logger
import org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib
import exquery.valuebeans.export.UserVO
import exquery.ClassSampleService
import exquery.ExperimentService
import exquery.ExperimentClassService

/**
 * User: pradeep
 * Date: Oct 7, 2010
 * Time: 5:57:57 PM
 * To get user specific details.
 */
class UserUtil {

  Logger gLogger = Logger.getLogger(UserUtil.class)
  private static UserUtil instance = null
  def g = new ApplicationTagLib()
  def experimentService = new ExperimentService()
  def classSampleService = new ClassSampleService()
  def experimentClassService = new ExperimentClassService()
     

  /**
   * returns the instance
   * @return
   */
  public static UserUtil getInstance() {
    if (instance == null) {
      instance = new UserUtil()
    }
    return instance
  }

    /**
     * to get user name by userId
     * @param userId
     * @return
     */
  def getUserNameByUserId(Long userId){
     SecUser user = SecUser.get(userId)

     if( user !=null ){
       return user.getUsername()
     }
  }

    /**
     * to get user display name by userId
     * @param userId
     * @return
     */
  def getUserDisplayNameByUserId(Long userId){
     SecUser user = SecUser.get(userId)

     if( user !=null ){
       return user.getDisplayname()
     }
  }

    /**
     * to get User Details by UserId or UserName or User Object
     * @param user
     * @return
     */
  UserVO getUserDetails(def user){
      UserVO userVO
      if(user!=null){
        SecUser secUser
        if(user instanceof Long){
            secUser = SecUser.get(user)
        }else if(user instanceof SecUser){
            secUser = user
        }else if(user instanceof String){
            secUser = SecUser.findByUsername(user)
        }

        gLogger.info "secUser :: ${secUser}"
        
        if(secUser!=null){
          gLogger.info "secUser.username :: ${secUser.username}"
          userVO = new UserVO()
          userVO.setUserId(secUser.id)
          userVO.setUserName(secUser.username)
          userVO.setDisplayName(secUser.displayname) 
          userVO.setEmail(secUser.email)
          gLogger.info "Result userVO :: ${userVO}"

          def experimentIds = experimentService.getExperimentIdsByUserId(secUser.id)

          gLogger.info "experimentIds :: ${experimentIds}"

          if( experimentIds!=null){
            if(experimentIds instanceof Collection && experimentIds.size()>0){
              gLogger.info "experimentIds :: ${experimentIds.class}"
              userVO.setExperimentCount(experimentIds.size())
              userVO.setClassesCount(experimentClassService.getClassesCountByExperimentIds(experimentIds))
              userVO.setSamplesCount(classSampleService.getSamplesCountByExperimentIds(experimentIds))
            }
          }

          gLogger.info "Result userVO :: ${userVO}"
        }
      }
      return userVO
    }




}
